package com.ynjt.db;

import java.sql.*;

public class DBOper {

    public Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/get_class?useUnicode=true&characterEncoding=utf-8&useSSL=false", "root", "admin");
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public boolean closeConnection(ResultSet rest, Statement stat, Connection conn){

        if (rest != null){
            try {
                rest.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stat != null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return true;
    }

    public int executeSQL(String sql){

        Connection conn = null;
        Statement stat = null;
        int res = 0;
        try {
            conn = getConnection();
            stat = conn.createStatement();
            res = stat.executeUpdate(sql);
            closeConnection(null, stat, conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return res;
    }

}
